/**
 * NG控制器 relationExtractionCtrl.js
 *
 * @author Wang Xiaodong
 */
indexApp.controller(
    'relationExtractionCtrl',
    function ($scope, $http, $timeout) {
        /**
         * 界面视图组件可见性设置
         */
        $scope.mysqlDbInfoVisible = false;
        $scope.mysqlDbTableSampleVisible = false;
        $scope.mysqlDbTableStrucVisible = false;
        $scope.sqlUserDefinedTableDataVisible = false;
        $scope.progressBarVisible = false;
        $scope.runExtractBtnShow = 0;

        /**
         * MySQL数据源配置对象
         */
        var mysqlConfig = $scope.mysqlConfig = {
            ip: "localhost",
            port: "33306",
            dbName: "pkdb",
            username: "root",
            password: "password",
        }

        /**
         * 连接MySQL数据库
         */
        $scope.connectMySQL = function () {
            $scope.mysqlDbTableSampleVisible = false;
            $scope.mysqlDbTableStrucVisible = false;

            var apiMySQLConnect = 'mysql/connect';
            $http({
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                url: apiMySQLConnect,
                data: $scope.mysqlConfig,

            }).then(function (resp, status) {
                console.log(resp);
                $scope.logForConnection = resp.data["message"];
                $scope.runExtractBtnShow = 1;
            }, function (resp, status) {
                $scope.resp = resp;
                $scope.status = status;
            });
        }

        /**
         * 关闭数据库连接（仅仅隐藏相关可视组件）
         */
        $scope.disconnectMySQL = function () {
            $scope.mysqlDbInfoVisible = false;
            $scope.mysqlDbTableSampleVisible = false;
            $scope.mysqlDbTableStrucVisible = false;
            $scope.runExtractBtnShow = 0;
        }

        /**
         * 查询MySQL数据库中所有表
         */
        var listMySQLTables = $scope.listMySQLTables = function () {
            $scope.mysqlDbInfoVisible = true;
            $scope.selected = [];
            var selectedTags = $scope.selectedTags = [];
            $scope.selectedTagsString = undefined;
            $scope.sqlStatement = undefined;

            var apiMySQLTables = 'mysql/tables';

            $http({
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                url: apiMySQLTables,
                data: mysqlConfig,
            }).then(function (resp, status) {
                console.log(resp);
                $scope.mysqlTables = resp.data["data"];
            }, function (resp, status) {
                $scope.resp = resp;
                $scope.status = status;
            });
        }

        $scope.currentMySQLTable = undefined;
        $scope.currentMySQLTableDesc = undefined;
        /**
         * 查询MySQL数据库中某表的结构
         */
        var getMySQLTableDesc = $scope.getMySQLTableDesc = function (
            tableName) {
            $scope.currentMySQLTable = tableName;
            $scope.selected = [];
            var selectedTags = $scope.selectedTags = [];
            $scope.selectedTagsString = undefined;
            $scope.sqlStatement = undefined;
            $scope.sqlUserDefinedTableDataVisible = false;
            $scope.sqlStatement = "SELECT * FROM " + tableName;

            var apiMySQLTableDesc = 'mysql/tables/'
                + tableName;

            $http({
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                url: apiMySQLTableDesc,
                data: mysqlConfig,
            }).then(function (resp, status) {
                console.log(resp);
                $scope.mysqlTableDesc[tableName] = resp.data["data"];
                $scope.currentMySQLTableDesc = resp.data["data"];
            }, function (resp, status) {
                $scope.resp = resp;
                $scope.status = status;
            });
        }

        /**
         * 查询MySQL数据库中某表查询样例（接口只返回5行样例数据）
         */
        var getMySQLTableSampleData = $scope.getMySQLTableSampleData = function (
            tableName) {

            var apiMySQLTableSampleData = 'mysql/select';

            mysqlConfig["sql"] = "SELECT * FROM " + tableName;

            $http({
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                url: apiMySQLTableSampleData,
                data: mysqlConfig,
            }).then(function (resp, status) {
                console.log(resp);
                $scope.mysqlTableSampleData = resp.data["data"];
                $scope.mysqlDbTableSampleVisible = true;
            }, function (resp, status) {
                $scope.resp = resp;
                $scope.status = status;
            });
        }


        /**
         * 处理table复选框
         */
        $scope.tableSelected = [];
        $scope.mysqlTableDesc = {};
        $scope.tableSelectedString = undefined;

        var updateTableSelected = function (action, id, name) {
            $scope.sqlUserDefinedTableDataVisible = false;
            $scope.mysqlDbTableSampleVisible = false;
            if (action == 'add'
                && $scope.tableSelected.indexOf(name) == -1) {
                $scope.tableSelected.push(name);
                $scope.getMySQLTableDesc(name);
            }

            if (action == 'remove'
                && $scope.tableSelected.indexOf(name) != -1) {
                var idx = $scope.tableSelected.indexOf(name);
                $scope.tableSelected.splice(idx, 1);
            }
            $scope.tableSelectedString = $scope.tableSelected.join(',');
        }

        $scope.updateTableSelection = function ($event, id) {
            var checkbox = $event.target;
            var action = (checkbox.checked ? 'add' : 'remove');
            updateTableSelected(action, id, checkbox.name);
            if ($scope.tableSelected.length == 0) {
                $scope.mysqlDbTableStrucVisible = false;
            } else {
                $scope.mysqlDbTableStrucVisible = true;
            }
        }

        $scope.isTableSelected = function (id, name) {
            return $scope.tableSelected.indexOf(name) >= 0;
        }

        /**
         * 处理字段复选框
         */
        $scope.columnSelected = {};
        $scope.columnSelectedString = {};
        $scope.selectedTagsString = undefined;
        $scope.columnSelectedNum = {};
        $scope.primaryKeySelected = {};
        $scope.primaryKeySelectedNum = {};
        var updateColumnSelected = function (action, id, table, type) {
            $scope.sqlUserDefinedTableDataVisible = false;

            if (type == "pk") {

                if (action == 'add'
                    && $scope.primaryKeySelected[table] != null) {
                    $scope.primaryKeySelected[table] = id;
                }

                if (action == 'remove'
                    && $scope.primaryKeySelected[table] == id) {
                    $scope.primaryKeySelected[table] = null;
                }

            } else {
                if (action == 'add'
                    && $scope.columnSelected[table].indexOf(id) == -1) {
                    $scope.columnSelected[table].push(id);
                }

                if (action == 'remove'
                    && $scope.columnSelected[table].indexOf(id) != -1) {
                    var idx = $scope.columnSelected[table].indexOf(id);
                    $scope.columnSelected[table].splice(idx, 1);
                }

                if ($scope.columnSelected[table].length != 0) {
                    $scope.selectedTagsString = $scope.selected
                        .join(', ');
                    $scope.sqlStatement = "SELECT "
                        + $scope.selectedTagsString + " FROM "
                        + $scope.currentMySQLTable;
                } else {
                    $scope.sqlStatement = "SELECT * FROM "
                        + $scope.currentMySQLTable;
                }
                $scope.columnSelectedString[table] = $scope.columnSelected[table].join(',');
            }
        }

        var initColumnSelected = function (table, type) {
            if (type == "pk") {
                if ($scope.primaryKeySelected[table] == null || $scope.primaryKeySelected[table] === undefined) {
                    $scope.primaryKeySelected[table] = [];
                }
                $scope.primaryKeySelectedNum[table] = $scope.primaryKeySelected[table].length;
            } else {
                if ($scope.columnSelected[table] == null || $scope.columnSelected[table] === undefined) {
                    $scope.columnSelected[table] = [];
                }
                $scope.columnSelectedNum[table] = $scope.columnSelected[table].length;
            }
        }

        $scope.updateColumnSelection = function ($event, id, table, type) {
            initColumnSelected(table, type);
            var checkbox = $event.target;
            var action = (checkbox.checked ? 'add' : 'remove');
            updateColumnSelected(action, id, table, type);
        }

        $scope.isColumnSelected = function (id, table, type) {
            initColumnSelected(table, type);

            if (type == 'pk') {

                return $scope.primaryKeySelected[table] == id;
            } else {

                return $scope.columnSelected[table].indexOf(id) >= 0;
            }
        }


        /**
         * 基于自定义SQL查询MySQL数据库中某表查询样例（接口只返回5行样例数据）
         */
        $scope.getMySQLTableSampleDataBySQL = function (sqlStatement) {
            $scope.sqlUserDefinedTableDataVisible = true;
            var apiMySQLTableSampleData = 'mysql/select';

            mysqlConfig["sql"] = sqlStatement;

            $http({
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                url: apiMySQLTableSampleData,
                data: mysqlConfig,
            }).then(
                function (resp, status) {
                    console.log(resp);
                    $scope.mysqlTableSampleDataBySQL = resp.data["data"];
                }, function (resp, status) {
                    $scope.resp = resp;
                    $scope.status = status;
                });
        }


        $scope.runExtractTask = function () {

            if (!$scope.tableSelected.length > 0) {
                swal({
                    title: '至少选择一个表',
                    timer: 2000
                })
                return;
            } else {
                for (var i = 0; i < $scope.tableSelected.length; i++) {
                    var tableName = $scope.tableSelected[i];
                    if ($scope.columnSelected[tableName].length < 2) {
                        swal({
                            title: '每个表需要选择两个数据字段，请检查表：' + tableName,
                            timer: 2000
                        })
                        return;
                    }
                    if ($scope.primaryKeySelected[tableName] < 1) {
                        swal({
                            title: '每个表需要选择一个主键字段，请检查表：' + tableName,
                            timer: 2000
                        });
                        return;
                    }
                }
            }

            $scope.runExtractBtnShow = 2;
            $http({
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                url: "extract",
                data: {
                    "tableName": $scope.tableSelectedString,
                    "columns": $scope.columnSelectedString,
                    "primaryKey": $scope.primaryKeySelected
                },
            }).then(
                function (resp, status) {

                    $scope.runExtractBtnShow = 1;
                    swal({
                        title: '任务执行成功',
                        timer: 2000
                    }).then(
                        function () {
                        },
                        // handling the promise rejection
                        function (dismiss) {
                            if (dismiss === 'timer') {
                                console.log('I was closed by the timer')
                            }
                        }
                    )

                }, function (resp, status) {
                    $scope.resp = resp;
                    $scope.status = status;

                    $scope.runExtractBtnShow = 1;
                });
        }
    });
